package com.cn.web.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cn.error.ErrorConstantUtil;
import com.cn.exception.MyException;
import com.cn.group.GroupDO;
import com.cn.user.UserGroupDO;
import com.cn.util.SnowflakeIdWorkerUtil;
import com.cn.web.user.mapper.UserGroupMapper;
import com.cn.web.user.service.UserGroupService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * description: UserGroupService <br>
 * date: 23.5.8 13:33 <br>
 * author: cn_yaojin <br>
 * version: 1.0 <br>
 */
@Service
@Slf4j
public class UserGroupServiceImpl implements UserGroupService {

    @Autowired
    private UserGroupMapper userGroupMapper;


    @Override
    public void checkExsitByUserId(String groupId) {
        QueryWrapper<UserGroupDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("group_id", groupId);
        long count = this.userGroupMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new MyException(ErrorConstantUtil.GROUP_USER_EXSIT_ERROR);
        }
    }


    @Override
    public void addGroupIds(Set<String> groupIds, String userId) {
        UserGroupDO groupEntity = new UserGroupDO();
        groupEntity.setUserId(userId);
        for (String groupId : groupIds) {
            groupEntity.setGroupId(groupId).setId(SnowflakeIdWorkerUtil.getId());
            this.userGroupMapper.insert(groupEntity);
        }
    }

    @Override
    public List<UserGroupDO> selectUserGroups(String userId) {
        QueryWrapper<UserGroupDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        var groups = this.userGroupMapper.selectList(queryWrapper);
        return groups;
    }

    @Override
    public void del(Long id) {
        this.userGroupMapper.deleteById(id);
    }

    @Override
    public void delByIds(Set<String> ids) {
        for (String id : ids) {
            this.userGroupMapper.deleteById(id);
        }
    }

    @Override
    public void delByUserId(String userId) {
        QueryWrapper<UserGroupDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        this.userGroupMapper.delete(queryWrapper);
    }

    @Override
    public List<GroupDO> listByUserId(String userId) {
        Map<String, Object> pd = new HashMap<>();
        pd.put("userId", userId);
        return this.userGroupMapper.listByUserId(pd);
    }

}
